<?php
#============================================================
# Function to load a template 
# Input: file name, array of tags
# Output: content of file after replacing tags
#============================================================ 

function loadTemplate($template_name, $tags) {
    $folders = explode('/', dirname($_SERVER['SCRIPT_NAME']));
    array_shift($folders);
    array_splice($folders, -3);
    $root = $_SERVER['DOCUMENT_ROOT'] . (isset($folders) && !empty($folders) ? '/' . implode('/', $folders) : '') . '/';
    $template_name = $root . 'staging/appable/templates/' . $template_name;
;
    $template = file_get_contents($template_name);
    return replaceTags($tags, $template);
}

#============================================================
# Function to replace Template tags
# Input: array of tags and template contents
# Output: content of template after replacing tags
#============================================================

function replaceTags($tags = '', $template) {

    if (is_array($tags) && !empty($tags) && $tags != '') {

        foreach ($tags as $k => $v) {

            if ($v) {

                $template = preg_replace('/<!--\s*IF\s+' . $k . '\s*-->(.*?)<!--\s*ELSE[^-]*-->.*?<!--\s*ENDIF\s+' . $k . '\s*-->/is', '\1', $template);

                $template = preg_replace('/<!--\s*IF\s+' . $k . '\s*-->(.*?)<!--\s*ENDIF\s+' . $k . '\s*-->/is', '\1', $template);
            }

            if (is_array($v) && preg_match('/<!--\s*BEGIN\s+' . $k . '\s*-->(.*?)<!--\s*END\s+' . $k . '\s*-->/is', $template, $matches)) {

                $subValue = "";

                foreach ($v as $subData) {

                    $subValue .= replaceTags($subData, $matches[1]);
                }

                $template = str_replace($matches[0], $subValue, $template);
            } else {

                $template = str_replace('{' . $k . '}', $v, $template);
            }
        }
    }

    // Remove any remaining block and conditional statement.

    $template = preg_replace('/<!--\s*BEGIN\s+(\w+)\s*-->.*?<!--\s*END\s+\1\s*-->/is', '', $template);

    $template = preg_replace('/<!--\s*IF\s+(\w+)\s*-->.*?<!--\s*ELSE[^-]*-->(.*?)<!--\s*ENDIF\s+\1\s*-->/is', '\2', $template);

    $template = preg_replace('/<!--\s*IF\s+(\w+)\s*-->.*?<!--\s*ENDIF\s+\1\s*-->/is', '', $template);

    return $template;
}

?>
